﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Controls;
using System.Globalization;
using System.Windows.Media;

namespace MyPublisher.Windows.Theme
{
    // used in GridView control to alternate the background of rows
    public sealed class BackgroundConverter : IValueConverter
    {
        private static BackgroundConverter _instance;

        public static BackgroundConverter Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new BackgroundConverter();
                return _instance;
            }
        }

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ListBoxItem item = (ListBoxItem)value;
            ListBox listBox = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;

            if (listBox == null)
                return Brushes.White;

            // Get the index of a ListViewItem
            int index = listBox.ItemContainerGenerator.IndexFromContainer(item);
            if (-1 == index)
                return Brushes.White;

            SolidColorBrush brush = new SolidColorBrush();
            if (index % 2 == 0)
            {
                brush.Color = Color.FromArgb(255, 255, 255, 255);
            }
            else
            {
                brush.Color = Color.FromArgb(255, 247, 241, 215);
            }

            return brush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
